package cn.valorin.data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.bukkit.Bukkit;

import cn.valorin.Main;

public class MySQL
{
	private boolean enable;
	
	public boolean isEnabled() { return enable; }
	
    private Connection connection;
    
    public void connect() {
        try {
            this.connection = DriverManager.getConnection(
            		Main.getInstance().getConfig().getString("MySQL.url"),
            		Main.getInstance().getConfig().getString("MySQL.user"),
            		Main.getInstance().getConfig().getString("MySQL.password"));
            final PreparedStatement ps = this.getMysql().prepareStatement(
            		"CREATE TABLE IF NOT EXISTS `plant_loc` (`world` TEXT,`x` INT,`y` INT,`z` INT,`type` INT);");
            ps.execute();
            ps.close();
            Bukkit.getServer().getConsoleSender().sendMessage("§b成功连接数据库");
            enable = true;
        }
        catch (Exception e) {
        	enable = false;
            e.printStackTrace();
            Bukkit.getServer().getConsoleSender().sendMessage("§c未能成功连接数据库");
        }
    }
    
    public void createPlant(
    		final String world,
    		final int x,
    		final int y,
    		final int z,
    		final int type) {
        try {
            final PreparedStatement ps = this.getMysql().prepareStatement(
            		"INSERT INTO plant_loc (world,x,y,z,type) VALUE('"+world+"',"+x+","+y+","+z+","+type+");");
            ps.execute();
            ps.close();
            return;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    public void removePlant(
    		final String world,
    		final int x,
    		final int y,
    		final int z,
    		final int type) {
        try {
            final PreparedStatement ps = this.getMysql().prepareStatement(
            		"DELETE FROM plant_loc WHERE world = '"+world+"' AND x = "+x+" AND y = "+y+" AND z = "+z+" AND type = "+type+";");
            ps.execute();
            ps.close();
            return;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    public boolean isPlant(
    		final String world,
    		final int x,
    		final int y,
    		final int z,
    		final int type) {
		try {
			ResultSet rs = connection.createStatement().executeQuery(
					"SELECT * FROM plant_loc WHERE world = '"+world+"' AND x = "+x+" AND y = "+y+" AND z = "+z+" AND type = "+type+";");
			if (rs == null) { return false; }
			if (rs.next()) { return true; }
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
    }
    
    public Connection getMysql() {
        return this.connection;
    }
    
    public void close() {
        try {
        	connection.close();
			Bukkit.getServer().getConsoleSender().sendMessage("§b数据库断开连接...");
		} catch (SQLException e) {
			e.printStackTrace();
		}
    }
}
